인스턴스 변수는 init 메소드 안에서 초기화하는 것이 좋습니다.
인스턴스 메소드의 첫 인자는 self(인스턴스 자신)입니다.
In [ ]:
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def has_right(self):
return True
In [ ]:
class Man(Person):
pass
In [ ]:
tom = Man('tom', 'M')
In [ ]:
tom is Man
In [ ]:
tom.name
isinstance(a, b)는 a가 b 클래스의 인스턴스 인지를 확인합니다.
In [ ]:
isinstance(tom, Man)
In [ ]:
isinstance(tom, Person)
issubclass(a, b)는 a가 b의 서브 클래스 인지를 확인합니다.
In [ ]:
issubclass(Man, Person)
Person 클래스를 상속하는 Woman 클래스를 만듭니다.
In [ ]:
class Woman(Person):
def __init__(self, name, weight):
super(Woman, self).__init__(name, 'F')
self.__weight = weight
def __get_weight(self):
return self.__weight
In [ ]:
jane = Woman('jane', 50)
_(underscore) 두개로 시작하는 함수나 변수는 네임 맹글링(mangling)을 합니다.
In [ ]:
jane._Woman__get_weight()
@property와 @name.setter 데코레이터를 사용하여 getter/setter 메소드를 구현할 수 있습니다.
In [ ]:
jane.name
In [ ]:
jane.name = 'suji'
In [ ]:
jane.name
In [ ]:
class Person2(object):
def __init__(self, name, gender):
self.__hidden_name = name
self.gender = gender
@property
def my_name(self):
return self.__hidden_name
@my_name.setter
def my_name(self, str):
self.__hidden_name = str
In [ ]:
jane = Person2('jane', 'F')
In [ ]:
jane.my_name
In [ ]:
jane.my_name = 'suji'
In [ ]:
jane.my_name
클래스 변수는 클래스 바디에 선언하고 보통 메소드 선언보다 앞서서 기술합니다.
클래스 메소드는 @classmethod 데코레이터를 사용하고 첫번째 인자는 클래스 자신입니다.
In [ ]:
class Person3(object):
population = 0
def __init__(self, name, gender):
self.name = name
self.gender = gender
Person3.population += 1
@classmethod
def increase(cls):
cls.population += 1
클래스 변수는 인스턴스와 클래스를 통해 접근할 수 있습니다.
In [ ]:
jane = Person3('jane', 'F')
In [ ]:
jane.population
In [ ]:
tom = Person3('tom', 'M')
In [ ]:
tom.population
In [ ]:
Person3.population
클래스 메소드는 인스턴스를 만들지 않고 클래스 내부 자료를 수정할 수 있습니다.
In [ ]:
Person3.increase()
In [ ]:
Person3.population
정적 메소드는 @staticmethod 데코레이터를 사용합니다.
정적 메소드는 인스턴스나 클래스 인자를 제공받지 않습니다.
In [ ]:
class Person4(object):
population = 0
def __init__(self, name, gender):
self.name = name
self.gender = gender
Person4.population += 1
@classmethod
def increase(cls):
cls.population += 1
@staticmethod
def desc():
print('Person is Animal')
In [ ]:
jane = Person4('jane', 'F')
In [ ]:
jane.population
정적 메소드는 클래스나 인스턴스의 자료를 변경하지 않으며 유틸리티 목적으로 사용됩니다.
In [ ]:
jane.desc()
In [ ]:
Person4.desc()
인스턴스 메소드와 클래스/정적 메소드 이름이 같을 경우 인스턴스 메소드 이름을 변수에 할당하여 우회합니다.
In [ ]:
class Person5(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
self.desc = self.__desc
def __desc(self):
print('%s is Person' % self.name)
@staticmethod
def desc():
print('Person is Animal')
In [ ]:
jane = Person5('jane', 'F')
In [ ]:
jane.desc()
In [ ]:
Person5.desc()
클래스도 독스트링을 지원합니다.
In [ ]:
class Man(Person):
'''this is subclass of Person'''
pass
In [ ]:
Man?
In [ ]:
help(Man)